package cn.com.web.Servlet;

import cn.com.domain.Student;
import cn.com.domain.User;
import cn.com.service.StudentService;
import cn.com.service.UserService;
import cn.com.service.impl.StudentServiceImpl;
import cn.com.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //添加学生时获取学生参数
        String sidstr = request.getParameter("sid");
        String stuname = request.getParameter("stuname");
        String sex = request.getParameter("sex");
        String academy = request.getParameter("academy");
        //转换sidstr为整数
        int sid=-1;
        try {
             sid = Integer.parseInt(sidstr);
        } catch (NumberFormatException e) {
            //如果错误
            response.getWriter().write("添加失败，学生ID必须是整数");
            response.getWriter().write("<a href='addStudent.jsp'>添加学生页面</a>\n");
            e.printStackTrace();
            return;
        }
        if (sid==-1){
            response.getWriter().write("添加失败，学生ID必须是整数");
            response.getWriter().write("<a href='addStudent.jsp'>添加学生页面</a>\n");
            return;
        }else if (sid==0) {
            response.getWriter().write("添加失败，学生ID不能为空");
            response.getWriter().write("<a href='addStudent.jsp'>添加学生页面</a>\n");
        }else {
            if (stuname.length()==0)
            {
                response.getWriter().write("添加失败，请输入学生姓名");
                response.getWriter().write("<a href='addStudent.jsp'>添加学生页面</a>\n");
            }
            else {
                if (!sex.equals("男") && !sex.equals("女")){
                    response.getWriter().write("添加失败，学生的性别未填或者错误");
                    response.getWriter().write("<a href='addStudent.jsp'>添加学生页面</a>\n");
                }else {
                    StudentService studentService=new StudentServiceImpl();
                    Student student=new Student(sid,stuname,sex,academy);
                    studentService.addStudent(student);
                    response.getWriter().write("添加成功");
                    String path = request.getContextPath();
                    response.getWriter().write("<a href='"
                            +path+
                            "/StudentListServlet  '>学生信息页面</a>\n");
                }
            }
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
